package com.mht2017.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 处理流的工具类
 *
 * @author Booynal
 *
 */
public class StreamUtil {

	/**
	 * 从输入流读取所用内容到输出流，完成之后关闭流
	 *
	 * @param in
	 *            输入流
	 * @param out
	 *            输出流
	 * @return 返回读取到的字节数
	 * @throws IOException
	 *             可能会抛出IO异常
	 */
	public static long transfer(InputStream in, OutputStream out) throws IOException {
		return transfer(in, out, true);
	}

	/**
	 * 从输入流读取所用内容到输出流，手动指定是否关闭流
	 *
	 * @param in
	 *            输入流
	 * @param out
	 *            输出流
	 * @param isClose
	 *            是否关闭流
	 * @return 返回读取到的字节数
	 * @throws IOException
	 *             可能会抛出IO异常
	 */
	public static long transfer(InputStream in, OutputStream out, boolean isClose) throws IOException {
		return transfer(in, out, isClose, 8192);
	}

	/**
	 * 从输入流读取所用内容到输出流，手动指定是否关闭流，手动指定缓冲区大小
	 *
	 * @param in
	 *            输入流
	 * @param out
	 *            输出流
	 * @param isClose
	 *            是否关闭流
	 * @param bufferSize
	 *            缓冲区大小
	 * @return 返回读取到的字节数
	 * @throws IOException
	 *             可能会抛出IO异常
	 */
	public static long transfer(InputStream in, OutputStream out, boolean isClose, int bufferSize) throws IOException {
		long count = 0;
		try {
			int len = -1;
			byte[] b = new byte[bufferSize];
			while (-1 != (len = in.read(b))) {
				out.write(b, 0, len);
				count += len;
			}
			out.flush();
		} catch (IOException e) {
			throw e;
		} finally {
			if (isClose) {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		}
		return count;
	}

	public static byte[] fetchAllData(InputStream in) throws IOException {
		return fetchAllData(in, true, 8192);
	}

	public static byte[] fetchAllData(InputStream in, boolean isClose, int bufferSize) throws IOException {
		if (null == in) {
			return new byte[0];
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream(in.available() > 0 ? in.available() : 0);
		byte[] b = new byte[bufferSize];
		int len = -1;
		try {
			while (-1 != (len = in.read(b))) {
				baos.write(b, 0, len);
			}
		} finally {
			if (isClose) {
				in.close();
			}
		}
		return baos.toByteArray();
	}

}
